package com.ld.service;

import com.ld.mapper.UsersMapper;
import com.ld.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private UsersMapper usersMapper;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1. 根据用户名查询用户对象
		Users user = new Users();
		user.setUsername(username);
		Users users = usersMapper.selectOne(user);
		if(users == null){
			throw new UsernameNotFoundException("用户名不存在!");
		}

		//2. 定义用户角色
		Collection<? extends GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
		//3. 返回用户对象
		return new User(username,users.getPassword(),auths);
	}
}
